<?php
/**
 * Created by ljhint on 2020/9/22.
 */

namespace App\Models;


use Illuminate\Support\Facades\Redis;
use App\Models\City;


class RedisCache
{

    static function Cache($name, $data = Null, $expired = 0 )
    {
        if (!$expired)  $expired = mt_rand(600,1200);
        if ($data !== Null){
            return Redis::setex('baiche_'.$name,$expired,json_encode($data));
        }else{
            $redisData = Redis::get('baiche_'.$name);
            if ($redisData) {
                return json_decode($redisData,true);
            }else{
                return false;
            }
        }
    }

    static function isHas($name):bool
    {
        return (Redis::get('baiche_'.$name) !== null) ? true : false;
    }

    /**
     * 返回城市缓存数据,如果在缓存里面没有,则从数据库提取数据缓存到redis,如果有,则直接从redis里面读取
     *
     * @return []
     */
    static function GetCacheCitys(){
        $city_arra = [];
        if(self::isHas('citys')){
            $city_arra = self::Cache('citys');
        }else{
            $city_arr = City::get(['id','cityname','pinyin','firstletter','ProvinceId','ProvinceName','areaname','shortname','ishotcity'])->toArray();
            foreach ($city_arr as $v){
                $city_arra[$v['ProvinceName']][] = $v;
            }
            self::Cache('citys',$city_arra);
        }
        return $city_arra;
    }
}
